package battleships;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 * BattleServlet class
 * Handles battle-related inputs, starting new games, creating users and etc.
 */
@WebServlet("/BattleServlet")
public class BattleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//to avoid cookies lasting beyond one deploy
	static int serverId = (int)(Math.random() * 91284214);
	
	Integer getUserId(HttpSession session) {
		synchronized(session) {
			Integer userId = (Integer)(session.getAttribute("userId"));
//			// If we redeploy, the following two lines will invalidate the old cookies
			Integer s_serverId = (Integer)(session.getAttribute("serverId"));
			if (userId == null || s_serverId == null || s_serverId != serverId) {
				userId = Handler.addUser();
				session.setAttribute("serverId", serverId);
				session.setAttribute("userId", userId);
			}
			return userId;
		}
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		Integer userId = getUserId(req.getSession());
		out.print(Handler.handleParams(userId, req.getParameterMap()));
	}
}
